package com.lcf.app.validation.config;

import com.lcf.common.web.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ChenFei
 * @date 2021/10/25
 * <p>
 * springboot 异常处理器
 */
@Slf4j
@RestControllerAdvice
public class ExceptionsHandler {

    @ExceptionHandler(ConstraintViolationException.class)
    public Result<String> validation(ConstraintViolationException e) {
        String message = e.getConstraintViolations()
                .stream()
                .map(error -> error.getMessage())
                .collect(Collectors.joining(";"));
        log.warn("请求参数异常:{}", message);
        return Result.fail(message);
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Result<String> validation(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        String collect = fieldErrors.stream().map(fieldError -> {
            String field = fieldError.getField();
            String message = fieldError.getDefaultMessage();
            return field + " : " + message;
        }).collect(Collectors.joining(" ; "));
        log.warn("请求参数异常:{}", collect);
        return Result.fail(collect);
    }

    @ExceptionHandler(Exception.class)
    public Result<String> exception(Exception e) {
        log.info("系统异常：ERROR：{}", e);
        return Result.fail(e.getMessage());
    }


}
